package com.rc.saas.mini.listener;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.common.push.AliyunPushUtil;
import com.rc.saas.mini.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.mini.common.sms.AliyunSmsUtil;
import com.rc.saas.mini.model.elec.ElecStation;
import com.rc.saas.mini.model.member.MemberAccountRecord;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.service.MiniSubscribeService;
import com.rc.saas.mini.service.elec.ElecStationService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.rc.RcNoticeNotificationService;
import com.rc.saas.mini.service.rc.RcOperatorAccountRecordService;
import com.rc.saas.mini.service.tenant.TenantService;
import com.rc.saas.mini.vo.charge.CommandStopReq;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zcg
 * @CreateDate: 2022/2/28 10:55
 */
@Component
public class Open2appListener {
    private static Logger logger = LogManager.getLogger(Open2appListener.class);
    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private MiniSubscribeService miniSubscribeService;
    @Autowired
    private RcOperatorAccountRecordService rcOperatorAccountRecordService;
    @Autowired
    private TenantService tenantService;
    @Autowired
    private RcNoticeNotificationService rcNoticeNotificationService;


    @Autowired
    private OrderInfoService orderInfoService;

    @RabbitListener(queues = "open2app_notify_stop_charge_result")
    public void open2appNotifyStopChargeResultListener(Message message, Channel channel) throws Exception {
        String msg = new String(message.getBody(), "UTF-8");
        logger.info("open2appNotifyStopChargeResultListener 收到了:{}", msg);


        //try {
        CommandStopReq commandStopReq = new Gson().fromJson(msg, CommandStopReq.class);

        //订单信息
        OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(commandStopReq.getOrderId());

        if(orderInfo==null){
            return;
        }
        ElecStation elecStation = elecStationService.selectByPrimaryKey(orderInfo.getElecStationId());
        //用户信息
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(commandStopReq.getMemberId());

        if (elecStation.getOccupyFree() == null) {
            elecStation.setOccupyFree(10);
        }
        if (memberInfo.getMobile() != null) {
            SendSmsResponse sendResult = new SendSmsResponse();
            // 尊敬的用户您好，充电已完成，请在${code}分钟内插回充电枪，否则将会收取一定的资源占用费
            sendResult = AliyunSmsUtil.sendSms(memberInfo.getMobile(), elecStation.getOccupyFree().toString(), AliyunSmsTemplateEnum.SMS_245870040, null);

            if (sendResult == null) {
                logger.error("{},短信系统异常", memberInfo.getMobile());
            }
        } else {
            logger.error("{},短信发送失败，无手机号", memberInfo.getMemberId());
        }
        rcNoticeNotificationService.addOrder(orderInfo.getOrderId());

        if ("2".equals(orderInfo.getOrderSource())) {

            miniSubscribeService.notification_stop_charge_result(commandStopReq);
        } else {


            //判断手机号格式以及停止原因非空

            if (memberInfo != null && StringUtils.isNotBlank(memberInfo.getMobile())
                    && memberInfo.getMobile().matches(HttpConstant.MOBILE_REGEX)
                    && orderInfo.getStopReason() != null) {

                String minute = "15";
                String body = null;

                //订单停止方式：0：手动停止  1：故障停止  2：充满停止 3：余额不足停止 4:紧急按钮停止;

                /**
                 * 停止方式
                 * 0: 用户手动停止充电；
                 * 1: 客户归属地运营商平台停止充电；
                 * 2: BMS 停止充电；
                 * 3: 充电机网络异常；
                 * 4: 连接器断开
                 * 5: 电价异常
                 * 6: 余额不足
                 * 7: 电流过低停止
                 * 8: 充满平台停止
                 * 9: 充满停止
                 * 10: 电池温度过高停止
                 * 11: 电流过高
                 * 12: 电压过高
                 * 13: 订单已结算
                 * 14: 刷卡停止
                 */
                if (elecStation != null) {
                    minute = elecStation.getOccupyFree().toString();
                }
                if (orderInfo.getStopReason() == 0 || orderInfo.getStopReason() == 1 || orderInfo.getStopReason() == 9 || orderInfo.getStopReason() == 8) {
                    body = "尊敬的用户您好，充电已完成，请在" + minute + "分钟内插回充电枪，否则将会收取一定的资源占用费";
                } else if (orderInfo.getStopReason() == 6) {
                    body = "尊敬的用户您好，充电停止，账户余额不足请充值";
                } else if (orderInfo.getStopReason() == 7) {
                    body = "尊敬的用户您好，充电故障停止，请重新启动或联系客服";
                }
                Map map = new HashMap();
                map.put("type", 0);
                map.put("outOrderNum", orderInfo.getOutOrderNum());
                map.put("orderId", orderInfo.getOrderId());
                //发送移动推送
                if (StringUtils.isNotBlank(body)) {
                    new AliyunPushUtil().pushNotice(memberInfo.getMobile(), body, new Gson().toJson(map));
                }

            }
        }

        //} catch (Exception e) {
        //    logger.error("open2appNotifyStopChargeResultListener 错误", e);
        //    return;
        //}
    }


    @RabbitListener(queues = "app_rc_operator_account_record")
    public void appRcOperatorAccountRecordListener(Message message, Channel channel) throws Exception {
        String msg = new String(message.getBody(), "UTF-8");
        logger.info("appRcOperatorAccountRecordListener 收到了:{}", msg);
        MemberAccountRecord memberAccountRecord = JSON.parseObject(msg, MemberAccountRecord.class);
        rcOperatorAccountRecordService.saveByMemberAcountRecord(memberAccountRecord);
        return;
    }
}
